package styledaco.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.ibatis.sqlmap.client.SqlMapClient;

import comm.util.CommUtil;
import comm.util.SoptHashMap;
import comm.util.SqlMapLoader;

public class StyleFlowServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3612906072649537292L;
	private SqlMapClient sqlMapper = SqlMapLoader.getInstance();
	
	private Logger logger = Logger.getLogger(StyleFlowServlet.class);
	private String curServerHost = ""; 
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String result = "";
		curServerHost = request.getServerName()+request.getContextPath();
		try {
			//1은 Style category번호
			ArrayList lt = (ArrayList)sqlMapper.queryForList("board.getListForFlow","1");
			result = parseToXML(lt);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		response.getWriter().write(result);
	}
	
	private String parseToXML(ArrayList lt) throws UnsupportedEncodingException{
		String result = "";
		result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><friends scope=\"all\">";
		for(int i= 0;i<lt.size();i++){
			SoptHashMap curMap = (SoptHashMap)lt.get(i);
			result+="<person>";
			
			result+="<imgUrl>"+getFirstImgUrl(CommUtil.NVL(curMap.get("BOARD_CONTENT"),""))+"</imgUrl>";
			result+="<title>"+URLEncoder.encode(CommUtil.NVL(curMap.get("BOARD_TITLE"),""), "UTF-8") +"</title>";
			result+="<articleLocation>"+CommUtil.NVL(curMap.get("CATEGORY_TYPE_NAME"), "Style")+"?a="+CommUtil.NVL(curMap.get("BOARD_SEQ"),"")+"</articleLocation>";
			
			result+="</person>";
		}
		result += "</friends>";
		return result;
	}
	
	private String getFirstImgUrl(String str){
		if(str.length()>0){

			if( str.indexOf("<img") > -1 && str.indexOf("/>")>0){
				
				str = str.substring(str.indexOf("<img"));
				str = str.substring(str.indexOf("src=")+4);
				str = str.substring(0,str.indexOf("/>"));
				str = str.substring(str.indexOf("\"")+1);
				str = str.substring(0, str.indexOf("\""));
				
				if(str.indexOf(curServerHost)<0){
					str = "data/default.jpg";
					//logger.debug("T_T우리서버 그림이 아니여 ㅠ_ㅠ");
				}
			}else{
				str = "data/default.jpg";
			}
			
		}else{
			str = "data/default.jpg";
		}
		
		//logger.debug("돌려주는 이미지 주소:"+str);
		return str;
	}

}
